//
//  XJCmtSearchReplicaVC.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/7/16.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  社区搜索复制品 

#import "XJCmtSearchReplicaVC.h"

//controller
#import "XJCmtIdentityVC.h" //点击社区---->跳转对应社区认证vc

// view
#import "RBSearchNaviBar.h"
#import "XJCommunitySearchTbView.h" // tableView
#import "XJCommunityHistoryView.h" // 搜索历史
#import "XJCommunityNearView.h" // 附近社区
#import "XJCommunitySearchResultView.h" //7-6 搜索结果view

// model
#import "XJCommunityModel.h" // 社区model
#import "RBDataBaseTool.h" //数据库工具类


@interface XJCmtSearchReplicaVC ()
/**搜索框*/
@property (nonatomic, strong) RBSearchNaviBar *searchNavView;
@property (nonatomic, strong) XJCommunitySearchTbView *defaultTv; // 默认状态下的tableView
@property (nonatomic, strong) XJCommunitySearchTbView *resultTv; // 搜索结果tv

/**附近小区*/
@property(nonatomic, strong) NSMutableArray *nearArr;
/**搜索历史*/
@property(nonatomic, strong) NSMutableArray *historyArr;

@property(nonatomic, strong) XJCommunityHistoryView *historyView;
@property(nonatomic, strong) XJCommunityNearView *nearView;
@property (nonatomic, strong) XJCommunitySearchResultView *searchResultView;
@end

@implementation XJCmtSearchReplicaVC

#pragma mark - 一 lazy
- (NSMutableArray *)nearArr {
    if (!_nearArr) {
        _nearArr = [NSMutableArray array];
    }
    return _nearArr;
}
- (NSMutableArray *)historyArr {
    if (!_historyArr) {
        _historyArr = [NSMutableArray array];
    }
    return _historyArr;
}

- (RBSearchNaviBar *)searchNavView {
    if (!_searchNavView) {
        _searchNavView = [[RBSearchNaviBar alloc] initWithFrame:CGRectMake(0, 20, KWidth, 64)];
        _searchNavView.searchBar.placeholder = @"请输入小区名称";
        
        XJWeakSelf(self)
        _searchNavView.cancelBlock = ^{
            [weakself.navigationController popViewControllerAnimated:YES];
        };
        
        _searchNavView.searchBlock = ^(NSString *searchStr) {
            [weakself requestSearchCommunity:searchStr];
        };
    }
    return _searchNavView;
}
// 统筹账户 OCT 甲类药

// 搜索结果tableView:默认隐藏
-  (XJCommunitySearchTbView *)resultTv {
    if (!_resultTv) {
        
        CGFloat y = CGRectGetMaxY(self.searchNavView.frame);
        _resultTv = [[XJCommunitySearchTbView alloc] initWithFrame:CGRectMake(0, y, KWidth, KHeight - y-XJTopNavH) style:(UITableViewStylePlain)];
    }
    return _resultTv;
}

// 默认tableview
- (XJCommunitySearchTbView *)defaultTv {
    if (!_defaultTv) {
        CGFloat y = CGRectGetMaxY(self.searchNavView.frame);
        
        _defaultTv = [[XJCommunitySearchTbView alloc] initWithFrame:CGRectMake(0, y, KWidth, KHeight - y - XJTopNavH) style:(UITableViewStylePlain)];
    }
    return _defaultTv;
}

- (XJCommunityHistoryView *)historyView {
    if (!_historyView) {
        _historyView = [[XJCommunityHistoryView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 100)]; //现在高度定死。
        
        
        XJWeakSelf(self);
        _historyView.clickTagBlock = ^(XJCommunityModel *cmtModel) {
            XJLog(@"======:%@",cmtModel.community_id);
            
            [weakself gotoXJCmtIdentityVCWithCmtId:cmtModel.community_id];
        };

        _historyView.deleteHistoryBlock = ^{
            //清空数据库
            [[RBDataBaseTool shareDataBase] deleteAllCommunityModel];
            NSMutableArray *historyArr  = [[RBDataBaseTool shareDataBase] queryAllCommunityModel];
            XJLog(@"清空数据库:%@ -- %ld",historyArr,historyArr.count);
            weakself.historyView.historyArr = historyArr;
            
            //把表头设置为 nil 不然 上边有一块空白。
            weakself.defaultTv.tableHeaderView = nil;
        };
    }
    return _historyView;
}


- (XJCommunityNearView *)nearView {
    if (!_nearView) {
        
        _nearView = [[XJCommunityNearView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 100)]; // 7-6 人家要固定高度。多余的 ...显示
        
        XJWeakSelf(self);
        
        _nearView.clickTagBlock = ^(XJCommunityModel *cmtModel) {
            //同一个model只添加一次不然会导致重复的内容
            [weakself rb_AddCommunityModelToDataSourceWithCommunity:cmtModel];
            [weakself gotoXJCmtIdentityVCWithCmtId:cmtModel.community_id];
        };
        
    }
    
    return _nearView;
}

- (XJCommunitySearchResultView *)searchResultView {
    if (!_searchResultView) {
        _searchResultView = [[XJCommunitySearchResultView alloc] initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight+20, KWidth, KHeight - kStatusBarAndNavigationBarHeight-20)];
        _searchResultView.hidden = YES;
        
        
        XJWeakSelf(self);
        _searchResultView.communitySearchResultViewDidSelectCellBlock = ^(XJCommunityModel *searchResultModel) {
            
            //通过名字判断:避免相同的model重复添加。
            [weakself rb_AddCommunityModelToDataSourceWithCommunity:searchResultModel];
            
            [weakself gotoXJCmtIdentityVCWithCmtId:searchResultModel.community_id];
        };
        
    }
    return _searchResultView;
}

#pragma mark - 二 view
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.searchNavView];
    
    //    [self.view addSubview:self.resultTv];
    [self requestData];
    
    [self setupDetaltTv];
}

- (void)setupDetaltTv {
    
    [self.view addSubview:self.defaultTv];
    
    self.defaultTv.tableHeaderView = self.historyView;
    //    XJCommunityModel *model = [[XJCommunityModel alloc] init];
    //    model.name = @"春波小区";
    //    self.historyView.historyArr = @[model].mutableCopy;
    
    //        self.historyView.historyArr = @[@"春波小区",@"太阳小区",@"彩虹小区",@"彩虹小区"].mutableCopy;
    
    self.defaultTv.tableFooterView = self.nearView;
    //    self.nearView.nearArray = @[@"辣区",@"春波小区",@"太阳小区",@"彩虹小彩虹熊去区",@"五个字效果"].mutableCopy;
    [self.defaultTv reloadData];
    
    
    //搜索结果view默认hidden。
    [self.view addSubview:self.searchResultView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    //取出本地保存的搜索历史数组 赋值 刷新
    NSMutableArray *resultArr = [[RBDataBaseTool shareDataBase] queryAllCommunityModel];
    XJLog(@"%@--%ld",resultArr,resultArr.count);
    if (resultArr.count == 0) {
        self.defaultTv.tableHeaderView = nil; // 如果没有数据就不给区头。不然会有一片空白的。
    }
    
    self.historyView.historyArr = resultArr;
    [self.defaultTv reloadData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    XJLog(@"");
}

#pragma mark - 网络请求
// 一进来就请求数据的接口
- (void)requestData {
    
    NSString *uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    XJLog(@"uuid:%@",uuid);
    if([NSString isEmptyString:uuid]) return;
    
    [XJHttpTool requestCommunityToSearchWithLat:self.lat lng:self.lng customId:uuid successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        NSArray *tempArr = responseObjc[@"data"][@"content"][@"community_list"];
        
        if ([code isEqualToString:@"0"]) {
            if (tempArr.count) {
                for (NSDictionary *dic in tempArr) {
                    XJCommunityModel *model = [XJCommunityModel mj_objectWithKeyValues:dic];
                    
                    [self.nearArr addObject:model];
                }
                
                // 刷新
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.nearView.nearArray = self.nearArr;
                    
                    [self.defaultTv reloadData];
                });
                
            }else {
                [MBProgressHUD showError:@"没有数据"];
            }
        }
        
    } fialH:^(NSError *error) {
        [MBProgressHUD showError:[error localizedDescription]];
    }];
}

// 搜索社区
- (void)requestSearchCommunity:(NSString *)name {
    
    [XJHttpTool requestCommunitySearchWithLng:self.lng lat:self.lat name:name successH:^(id responseObjc) {
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        XJLog(@"%@",jsonStr);
        
        self.searchResultView.hidden = NO;
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSArray *community_list = responseObjc[@"data"][@"community_list"];
                NSMutableArray *tempArr = [NSMutableArray array];
                
                for (NSDictionary *dic in community_list) {
                    XJCommunityModel *model = [XJCommunityModel mj_objectWithKeyValues:dic];
                    [tempArr addObject:model];
                }
                
                self.searchResultView.dataArray = tempArr;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.searchResultView cmtSearchResultViewReload];
                });
            }
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
        XJLog(@"%@",[error localizedDescription]);
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark - 搜索逻辑
/**
 1.搜索结果view 把 其他view 覆盖掉了
 2.搜索成功将搜索的数据保存到搜索历史数组中。
 3.点击搜索结果返回到上一界面
 
 这里需要将搜索历史保存到本地。
 
 
 
 4.再次进入展示搜索历史。view
 
 */

#pragma mark -  Private method
//通过一个model只存一次。目前只能通过判断名字是否一样来处理。
- (void)rb_AddCommunityModelToDataSourceWithCommunity:(XJCommunityModel *)cmtModel {
    NSMutableArray *modelArr = [[RBDataBaseTool shareDataBase] queryAllCommunityModel];
    NSMutableArray *nameArr = [NSMutableArray array];
    for (XJCommunityModel *model  in modelArr) {
        [nameArr addObject:model.name];
    }
    
    if (![nameArr containsObject:cmtModel.name]) {
        [[RBDataBaseTool shareDataBase] addCommunityModel:cmtModel];
    }
}



/**
 跳转到社区认证VC

 @param communityId 社区id
 */
- (void)gotoXJCmtIdentityVCWithCmtId:(NSString *)communityId  {
    XJCmtIdentityVC *cmtIdVC = [XJCmtIdentityVC new];
    cmtIdVC.communityId = communityId;
    [self.navigationController pushViewController:cmtIdVC animated:YES];
}
@end

